package com.avocado.bt.impl;

import com.avocado.bt.IBTContext;
import com.avocado.bt.IBTNode;

import java.util.Stack;

/**
 * @author avocado
 * @date 2023/10/16 22:07
 */
public class TreeBuilder {

    private final IBTContext context;
    private final Stack<IBTNode> ibtNodes = new Stack<>();
    private IBTNode root = null;

    public TreeBuilder(IBTContext context) {
        this.context = context;
    }

    public TreeBuilder addBehaviour(IBTNode node) {
        node.setContent(context);
        // 如果没有根节点设置新节点为根节点,否则设置新节点为堆栈顶部节点的子节点
        if (root == null) {
            root = node;
        } else {
            IBTNode peek = ibtNodes.peek();
            peek.addChildNode(node);
            node.setParent(peek);
        }
        // 最新的节点永远在栈顶
        ibtNodes.push(node);
        return this;
    }

    public TreeBuilder back() {
        ibtNodes.pop();
        return this;
    }

    public Tree build() {
        while (!ibtNodes.empty()) {
            ibtNodes.pop();
        }
        return new Tree(root);
    }

}
